package com.googlecode.spruce.plugins.core.network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import com.googlecode.spruce.core.DefaultPluginResult;
import com.googlecode.spruce.core.ServiceCheckPlugin;
import com.googlecode.spruce.core.ServiceCheckPluginResult;

/**
 * Test whether a host is reachable. Best effort is made by the implementation
 * to try to reach the host, but firewalls and server configuration may block
 * requests resulting in a unreachable status while some specific ports may be
 * accessible. A typical implementation will use ICMP ECHO REQUESTs if the
 * privilege can be obtained, otherwise it will try to establish a TCP
 * connection on port 7 (Echo) of the destination host.
 * 
 * The timeout value, in milliseconds, indicates the maximum amount of time the
 * try should take. If the operation times out before getting an answer, the
 * host is deemed unreachable.
 */
public class HostReachableServiceCheck implements ServiceCheckPlugin
{

    private String host;

    private int timeout = 1000;

    public ServiceCheckPluginResult execute()
    {
        final InetAddress ipAddress;

        try
        {
            ipAddress = InetAddress.getByName(this.host);

            if (!ipAddress.isReachable(this.timeout))
            {
                return new DefaultPluginResult("Could not find availability of host: " + this.host);
            }
        }
        catch (final UnknownHostException e)
        {
            return new DefaultPluginResult("Unknown host: " + this.host);
        }
        catch (final IOException e)
        {
            return new DefaultPluginResult("Unknown host: " + this.host);

        }

        return new DefaultPluginResult(100);
    }

    /**
     * @return the host
     */
    public String getHost()
    {
        return host;
    }

    /**
     * @param host
     *            the host to set
     */
    public void setHost(final String host)
    {
        this.host = host;
    }

    /**
     * @return the timeout
     */
    public int getTimeout()
    {
        return timeout;
    }

    /**
     * @param timeout
     *            the timeout to set
     */
    public void setTimeout(final int timeout)
    {
        this.timeout = timeout;
    }

}
